import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import { AccountAPI } from '@/api/user.js'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken() || '')
  const userInfo = ref(getUserInfo() || null)
  const isLoggedIn = ref(!!getToken())

  // 计算属性
  const hasUserInfo = computed(() => !!userInfo.value)
  const userId = computed(() => userInfo.value?.id || '')
  const nickname = computed(() => userInfo.value?.nickname || '')
  const avatar = computed(() => userInfo.value?.avatar || '')
  const phone = computed(() => userInfo.value?.phone || '')

  // 登录
  const login = async (loginData) => {
    try {
      const result = await AccountAPI.phoneLoginByPassword({
        phone: loginData.phone,
        accountType: loginData.accountType || 1,
        password: loginData.password
      })
      
      if (result.code === 0) {
        const { token: newToken, userInfo: newUserInfo } = result.data
        
        console.log('密码登录成功，获取到的token:', newToken)
        
        // 保存到本地存储
        setToken(newToken)
        setUserInfo(newUserInfo)
        
        // 更新状态
        token.value = newToken
        userInfo.value = newUserInfo
        isLoggedIn.value = true
        
        return result
      } else {
        throw new Error(result.msg || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 手机验证码登录
  const loginByCode = async (loginData) => {
    try {
      const result = await AccountAPI.phoneLoginByCode({
        phone: loginData.phone,
        accountType: loginData.accountType || 1,
        code: loginData.code,
        codeType: loginData.codeType || 1
      })
      
      if (result.code === 0) {
        const { token: newToken, userInfo: newUserInfo } = result.data
        
        console.log('验证码登录成功，获取到的token:', newToken)
        
        // 保存到本地存储
        setToken(newToken)
        setUserInfo(newUserInfo)
        
        // 更新状态
        token.value = newToken
        userInfo.value = newUserInfo
        isLoggedIn.value = true
        
        return result
      } else {
        throw new Error(result.msg || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 第三方登录
  const thirdPartyLogin = async (loginData, loginType) => {
    try {
      let result
      
      switch (loginType) {
        case 'wechat':
          result = await AccountAPI.wechatLogin(loginData)
          break
        case 'qq':
          result = await AccountAPI.qqLogin(loginData)
          break
        case 'apple':
          result = await AccountAPI.appleLogin(loginData)
          break
        default:
          throw new Error('不支持的登录方式')
      }
      
      if (result.code === 0) {
        const { token: newToken, userInfo: newUserInfo } = result.data
        
        console.log(`第三方登录(${loginType})成功，获取到的token:`, newToken)
        
        // 保存到本地存储
        setToken(newToken)
        setUserInfo(newUserInfo)
        
        // 更新状态
        token.value = newToken
        userInfo.value = newUserInfo
        isLoggedIn.value = true
        
        return result
      } else {
        throw new Error(result.msg || '登录失败')
      }
    } catch (error) {
      console.error('第三方登录失败:', error)
      throw error
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const result = await AccountAPI.getUserInfo({})
      
      if (result.code === 0) {
        const newUserInfo = result.data
        
        // 更新本地存储和状态
        setUserInfo(newUserInfo)
        userInfo.value = newUserInfo
        
        return newUserInfo
      } else {
        throw new Error(result.msg || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    setUserInfo(userInfo.value)
  }

  // 退出登录
  const logout = async () => {
    try {
      // 调用退出登录接口
      if (token.value) {
        await AccountAPI.logout({})
      }
    } catch (error) {
      console.error('退出登录接口调用失败:', error)
    } finally {
      // 清除本地数据
      removeToken()
      removeUserInfo()
      
      // 重置状态
      token.value = ''
      userInfo.value = null
      isLoggedIn.value = false
    }
  }

  // 检查登录状态
  const checkLoginStatus = () => {
    const currentToken = getToken()
    const currentUserInfo = getUserInfo()
    
    if (currentToken && currentUserInfo) {
      token.value = currentToken
      userInfo.value = currentUserInfo
      isLoggedIn.value = true
      return true
    } else {
      // 清除无效数据
      removeToken()
      removeUserInfo()
      token.value = ''
      userInfo.value = null
      isLoggedIn.value = false
      return false
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const result = await AccountAPI.loginByToken({})
      
      if (result.code === 0) {
        const { token: newToken } = result.data
        
        // 更新token
        setToken(newToken)
        token.value = newToken
        
        return newToken
      } else {
        throw new Error(result.msg || '刷新token失败')
      }
    } catch (error) {
      console.error('刷新token失败:', error)
      // token刷新失败，清除登录状态
      logout()
      throw error
    }
  }

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    
    // 计算属性
    hasUserInfo,
    userId,
    nickname,
    avatar,
    phone,
    
    // 方法
    login,
    loginByCode,
    thirdPartyLogin,
    fetchUserInfo,
    updateUserInfo,
    logout,
    checkLoginStatus,
    refreshToken
  }
}) 